package com.wyu.blog.component;

import com.wyu.blog.entity.Article;
import com.wyu.blog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class ArticleClickInterceptor implements HandlerInterceptor {

    @Autowired
    private ArticleService articleService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        Integer id = Integer.parseInt(request.getServletPath().split("/")[3]);
        Article article = articleService.findArticleById(id);

        HttpSession session = request.getSession();
        synchronized (session){
            if(session.getAttribute("article"+id) == null) {
                session.setAttribute("article" + id, id);
                article.setArticleViewCount(article.getArticleViewCount() + 1);
                articleService.updateView(article);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
